<template>
  <div class="X_Plot_content">
    <div class="X_Plot_content_right">
      <!-- right  -->
      <div class="X_Plot_right">
        <div style="
            height: 51px;
            display: flex;
            justify-content: flex-start;
            position: relative;
            top: 6px;
            right: 0px;
          ">
          <div v-for="(item, index) in filteredActiveArr" :key="index" style="position: relative; cursor: pointer"
            class="X_Plot_right_btn" @click="cliactive(item)">
            <img width="74px" height="51px" :src="getAssetsFile(item.src.imgname, item.src.imgurl)" />
            <span class="X_Plot_right_btn_title" style="position: absolute; left: 5px; top: 10px" :style="{
              color:
                rightbtn === item.title
                  ? '#1FF9D9'
                  : 'rgba(255,255,255,0.32)',
            }">{{ item.title }}</span>
          </div>
        </div>
        <!--  -->
        <div class="X_Plot_right_contcent">
          <div style="
              width: 280px;
              padding-top: 30px;
              margin-left: 32px;
              display: flex;
              align-items: center;
            ">
            <div style="position: relative; width: 238px" :style="{
              width: ['图层控制', '战场环境'].includes(rightbtn)
                ? '238px'
                : '280px',
            }">
              <el-input class="inputbox" v-model="filterText" placeholder="请输入搜索" />

              <img style="
                  position: absolute;
                  right: 12px;
                  top: 6px;
                  width: 20px;
                  height: 20px;
                " src="@/assets/img/27/riearch.png" />
            </div>
            <img v-if="['图层控制', '战场环境'].includes(rightbtn)" style="
                width: 20px;
                height: 20px;
                margin-left: 8px;
                cursor: pointer;
              " src="@/assets/img/27/ridaochu.png" />
            <img v-if="['图层控制', '战场环境'].includes(rightbtn)" style="
                width: 20px;
                height: 20px;
                margin-left: 13px;
                cursor: pointer;
              " src="@/assets/img/27/rishuaxin.png" @click="cliactive({ title: rightbtn })" />
          </div>



          <template v-if="rightbtn == '图层控制'">
            <el-tree v-if="treedata.length > 0" style="
              width: 280px;
              margin-top: 10px;
              margin-left: 32px;
              overflow-x: hidden;
              height: calc(100% - 80px);
            " ref="treeRef" node-key="id" draggable :props="props" @node-drop="handleDrop" :data="treedata"
              show-checkbox @node-contextmenu="ribtn" :filter-node-method="filterNode" @check-change="handleCheckChange"
              :expand-on-click-node="false">

              <template #default="{ node, data }">
                <!--  -->
                <template v-if="data.LayerType == 1">
                  <el-popover placement="right" trigger="click" :visible="data.popovisible">
                    <div v-for="item in [
                      {
                        url: 'tuceng',
                        btn: '',
                        tit: '新建图层',
                      },
                      {
                        url: 'shanchu',
                        btn: '',
                        tit: '删除图层',
                      },
                      // {
                      //   url: 'chmm',
                      //   btn: '',
                      //   tit: '重命名',
                      // },

                    ]" :key="item">
                      <div style="display: flex; padding: 5px 0; cursor: pointer" @click="treepopo(item, node, data)">
                        <img style="margin-right: 8px" width="16px" height="16px" :src="getAssetsFile(item.url)" />
                        <div>{{ item.tit }}</div>
                      </div>
                    </div>

                    <el-popover placement="right" trigger="click" :visible="data.subPopoverVisible">
                      <div style="padding: 10px;">
                        <div v-for="(poitem) in [
                          {
                            url: 'leftic/dian',
                            btn: 'leftic/dianbtn',
                            tit: '点',
                            num: 1,
                          },
                          {
                            url: 'leftic/xian',
                            btn: 'leftic/xianbtn',
                            tit: '线',
                            num: 2,
                          },
                          // {
                          //   url: 'leftic/ju',
                          //   btn: 'leftic/jubtn',
                          //   tit: '矩形',
                          //   num: 3,
                          // },
                          {
                            url: 'leftic/yuan',
                            btn: 'leftic/yuanbtn',
                            tit: '圆',
                            num: 4,
                          },
                          {
                            url: 'leftic/duo',
                            btn: 'leftic/duobtn',
                            tit: '多边形',
                            num: 5,
                          },
                          {
                            url: 'leftic/tuoyuan',
                            btn: 'leftic/tuoyuanbtn',
                            tit: '椭圆',
                            num: 13,
                          },
                          {
                            url: 'leftic/shan',
                            btn: 'leftic/shanbtn',
                            tit: '扇形',
                            num: 14,
                          },
                          {
                            url: 'leftic/shan',
                            btn: 'leftic/shanbtn',
                            tit: '扇环',
                            num: 15,
                          },
                          // {
                          //   url: 'leftic/shan',
                          //   btn: 'leftic/shanbtn',
                          //   tit: '测向线',
                          //   num: 16,
                          // },
                          // {
                          //   url: 'leftic/shan',
                          //   btn: 'leftic/shanbtn',
                          //   tit: '航迹线',
                          //   num: 17,
                          // },
                        ]" :key="poitem">
                          <div style="display: flex; padding: 5px 0; cursor: pointer"
                            @click="actpopoImage(poitem, node, data)">
                            <img style="margin-right: 8px" width="16px" height="16px"
                              :src="getAssetsFile(poitem.url)" />
                            <div>
                              {{ poitem.tit }}
                            </div>
                          </div>
                        </div>

                      </div>
                      <template #reference>

                        <div style="display: flex; padding: 5px 0; cursor: pointer" @click.stop="treepopo({
                          url: 'tuyuan',
                          btn: '',
                          tit: '新建图元',

                        }, node, data)">
                          <img style="margin-right: 8px" width="16px" height="16px" :src="getAssetsFile('tuyuan')" />
                          <div>新建图元</div>
                        </div>
                      </template>
                    </el-popover>



                    <template #reference>
                      <div style="
                      width: 90%;
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    ">
                        <div>{{ data.LayerName }}</div>


                      </div>
                    </template>
                  </el-popover>
                </template>
                <!--  -->
                <template v-else>
                  <el-popover placement="right" trigger="click" :visible="data.popovisible">
                    <div v-for="item in [
                      // {
                      //   url: 'chmm',
                      //   btn: '',
                      //   tit: '重命名',
                      // },
                      {
                        url: 'edit',
                        btn: '',
                        tit: '编辑',
                      },
                      {
                        url: 'shanchu',
                        btn: '',
                        tit: '删除',
                      },
                    ]" :key="item">
                      <div style="display: flex; padding: 5px 0; cursor: pointer" @click="treepopo(item, node, data)">
                        <img style="margin-right: 8px" width="16px" height="16px" :src="getAssetsFile(item.url)" />
                        <div>{{ item.tit }}</div>
                      </div>
                    </div>
                    <template #reference>
                      <div style="
                      width: 90%;
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    ">
                        <div>{{ data.LayerName }}</div>


                      </div>
                    </template>
                  </el-popover>
                </template>

              </template>
            </el-tree>
          </template>
          <template v-if="rightbtn == '目标属性'">
            <el-tree v-if="treedata.length > 0" style="
              width: 280px;
              margin-top: 10px;
              margin-left: 32px;
              overflow-x: hidden;
              height: calc(100% - 80px);
            " ref="treeRef" node-key="id" :props="props" :data="treedata" show-checkbox :current-node-key="5"
              @check-change="handleCheckChangess" :filter-node-method="filterNode">


            </el-tree>
          </template>
          <template v-if="rightbtn == '目标消息'">
            <el-tree v-if="treedata.length > 0" style="
              width: 280px;
              margin-top: 10px;
              margin-left: 32px;
              overflow-x: hidden;
              height: calc(100% - 80px);
            " ref="treeRef" node-key="id" :props="props" :data="treedata" show-checkbox @node-contextmenu="ribtnss"
              :filter-node-method="filterNode" @check-change="handleCheckChangemu">
              <template #default="{ node, data }">

                <el-popover placement="right" trigger="click" :visible="data.popovisible">
                  <div v-for="item in getMenuItems(data)" :key="item.url">
                    <div class="treepopomes" style="display: flex; padding: 8px 0; cursor: pointer"
                      @click="treepopo(item, node, data)">
                      <img style="margin-right: 8px" width="16px" height="16px" :src="getAssetsFile(item.url)" />
                      <div>{{ item.tit }}</div>
                    </div>
                  </div>
                  <template #reference>
                    <div style="
                      width: 90%;
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    ">
                      <div>{{ data.KeyValue }} {{ data.LayerName }}</div>
                    </div>
                  </template>

                </el-popover>

              </template>

            </el-tree>
          </template>
          <template v-if="rightbtn == '战场环境'">
            <el-tree v-if="treedata.length > 0" style="
              width: 280px;
              margin-top: 10px;
              margin-left: 32px;
              overflow-x: hidden;
              height: calc(100% - 80px);
            " ref="treeRef" node-key="id" :props="props" :data="treedata" show-checkbox
              :filter-node-method="filterNode" @node-click="handleCloudNodeClick">


            </el-tree>
          </template>
        </div>
      </div>
    </div>
    <!-- 纬度切换  -->
    <div class="lvlantubox" :style="{ left: boxLeft }">
      <div v-if="isnum" class="cont" ref="contref" v-for="(itm, index) in contItems" :key="index"
        @click="handleContClick(itm)" :class="{ actbtn: actiob.id === itm.id }">
        <img v-if="itm?.icon" class="contimg" :src="itm?.icon" />
        <span v-else class="contimg-span" style="line-height: 80px; color: black">
          {{ itm.name }}
        </span>
        <img v-if="actiob.id === itm.id" class="iconimg" :src="itm?.icon" />
        <img v-if="actiob.id === itm.id" class="iconimg" width="28px" height="28px"
          :src="getAssetsFile('27', 'youjiaobiao')" />
      </div>

      <div v-else class="cont actbtn" ref="contref" @click="handleContClick(actiob)">
        <img v-if="actiob?.icon" class="contimg" :src="actiob.icon" />
        <span v-else class="contimg-span">
          {{ actiob.name }}
        </span>
        <img class="iconimg" width="28px" height="28px" :src="getAssetsFile('27', 'youjiaobiao')" />
      </div>
    </div>
  </div>
  <!--  -->

  <!--  -->
</template>


<script setup>
import { ref, onMounted, onBeforeUnmount, getCurrentInstance, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAssetsFile } from "@/utils/compnt";
const { proxy } = getCurrentInstance();
import { CloudManager, CesiumWeather, LayerOceanCurrent } from "@/utils/cesiumExp-plot/src/index.js";



import { WindLayer } from '@/utils/cesiumExp-plot/src/js/meteorology/feng/cesium-wind.js';

import { getLayer, postAddLayer, putLayer, deleteLayer, getmessag } from "@/api"




import { useWebSocketStore } from '@/stores/websocket';
const websocketStore = useWebSocketStore();
import { useTitleStore } from '@/stores/TitleStore'; // 添加这行
const titleStore = useTitleStore(); // 添加这行
// 数据

const getMenuItems = (data) => {
  return [
    {
      url: 'tuceng',
      btn: '',
      tit: data?.KeyValue || '', // 提供默认值
    },
    {
      url: 'shanchu',
      btn: '',
      tit: '目标消批',
    },
    {
      url: 'edit',
      btn: '',
      tit: '目标干预',
    },
  ];
};

const rightbtn = ref("图层控制");

const activearr = ref([
  {
    src: {
      imgname: "27",
      imgurl: "leftbtnbg",
    },
    title: "图层控制",
  },
  {
    src: {
      imgname: "27",
      imgurl: "ribtnbg",
    },
    title: "目标属性",
  },

  {
    src: {
      imgname: "27",
      imgurl: "ribtnbg",
    },
    title: "目标消息",
  },
  {
    src: {
      imgname: "27",
      imgurl: "ribtnbg",
    },
    title: "战场环境",
  },
]);
const filteredActiveArr = ref(titleStore.rightTitles.length > 0 ?
  activearr.value.filter(item => titleStore.rightTitles.includes(item.title)) :
  [...activearr.value]
);
const props = ref({
  children: "Children",
  label: "LayerName",
});
const treedata = ref([]);

const clicktree = ref("");

const contItems = ref([
  {
    id: 1,
    name: "二维",
    // icon:''
  },
  {
    id: 2,
    name: "三维",
    // icon:''
  },
]);
const treeRef = ref()
const activeIndex = ref(1);
const boxLeft = ref("-90px");
const isnum = ref(false);
const actiob = ref({
  name: "三维",
});

// el-tree 多选

const checkedNodes = ref([]) // 存储选中的节点数据

const handleCheckChange = (data, checked, indeterminate) => {
  // 获取所有选中的节点（包含半选状态的子节点）
  checkedNodes.value = treeRef.value.getCheckedNodes(false, false)
  console.log('选中的节点数据:', checkedNodes.value)
  // 可以在这里触发其他业务逻辑，如将选中数据传递给父组件等
  proxy.$mitt.emit('checkedNodestu', checkedNodes.value)
}
const handleCheckChangemu = (data, checked, indeterminate) => {
  // 获取所有选中的节点（包含半选状态的子节点）
  checkedNodes.value = treeRef.value.getCheckedNodes(false, false)
  // console.log('选中的节点数据:', checkedNodes.value)
  // 可以在这里触发其他业务逻辑，如将选中数据传递给父组件等
  proxy.$mitt.emit('checkedNodesmu', checkedNodes.value)
}


const handleCheckChangess = (data, checked, indeterminate) => {
  // 获取所有选中的节点（包含半选状态的子节点）
  let obj = []
  checkedNodes.value = treeRef.value.getCheckedNodes(false, false)
  console.log('选中的节点数据:', checkedNodes.value)
  const uniqueValues = new Set(); // 用于存储唯一值
  checkedNodes.value.forEach((e) => {
    const asdasd = e.id.split('-');
    const mapping = {
      '1': '水面',
      '2': '陆地',
      '3': '空中',
      '4': '设施',
      '5': '空间'
    };
    if (mapping[asdasd[0]]) {
      uniqueValues.add(mapping[asdasd[0]]);
    }
  });
  obj = Array.from(uniqueValues); // 将 Set 转换为数组赋值给 obj
  // fater
  // 可以在这里触发其他业务逻辑，如将选中数据传递给父组件等
  proxy.$mitt.emit('checkedNodesChangedddd', {
    fa: obj,
    che: checkedNodes.value
  })
}







// 方法
const cliactive = (item) => {
  rightbtn.value = item.title;
  filterText.value = ''
  switch (item.title) {
    case "图层控制":
      getLayerapi()
      break;

    case "目标属性":

      treedata.value = [
        {
          id: '1',
          LayerName: '水面',
          Children: [
            {
              id: '1-1',
              LayerName: '敌'
            },
            {
              id: '1-2',
              LayerName: '我'
            },
            {
              id: '1-3',
              LayerName: '友'
            },
            {
              id: '1-4',
              LayerName: '中立'
            },
            {
              id: '1-5',
              LayerName: '不明'
            },

          ]
        },
        {
          id: '2',
          LayerName: '陆地',
          Children: [
            {
              id: '2-1',
              LayerName: '敌'
            },
            {
              id: '2-2',
              LayerName: '我'
            },
            {
              id: '2-3',
              LayerName: '友'
            },
            {
              id: '2-4',
              LayerName: '中立'
            },
            {
              id: '2-5',
              LayerName: '不明'
            },

          ]
        },
        {
          id: '3',
          LayerName: '空中',
          Children: [
            {
              id: '3-1',
              LayerName: '敌'
            },
            {
              id: '3-2',
              LayerName: '我'
            },
            {
              id: '3-3',
              LayerName: '友'
            },
            {
              id: '3-4',
              LayerName: '中立'
            },
            {
              id: '3-5',
              LayerName: '不明'
            },

          ]
        },
        {
          id: '4',
          LayerName: '设施',
          Children: [
            {
              id: '4-1',
              LayerName: '敌'
            },
            {
              id: '4-2',
              LayerName: '我'
            },
            {
              id: '4-3',
              LayerName: '友'
            },
            {
              id: '4-4',
              LayerName: '中立'
            },
            {
              id: '4-5',
              LayerName: '不明'
            },

          ]
        },
        {
          id: '5',
          LayerName: '空间',
          Children: [
            {
              id: '5-1',
              LayerName: '敌'
            },
            {
              id: '5-2',
              LayerName: '我'
            },
            {
              id: '5-3',
              LayerName: '友'
            },
            {
              id: '5-4',
              LayerName: '中立'
            },
            {
              id: '5-5',
              LayerName: '不明'
            },

          ]
        },


      ]
      break;

    case "目标消息":
      getmessagapi()
      break;

    case "战场环境":
      treedata.value = [
        {
          LayerName: '数字高程模型',
        },
        {
          LayerName: '数字表面模型',
        },
        {
          LayerName: '数字正射影像',
        },
        {
          LayerName: '气象水文图层',
          Children: [
            {
              LayerName: '云'
            },
            {
              LayerName: '风'
            },
            {
              LayerName: '海浪'
            },
            {
              LayerName: '雷电'
            },
          ]
        }

      ]
      break;
  }
};

const handleDrop = async (fist, last, view, event) => {
  console.log('fist', fist)
  console.log('last', last)
  console.log('view', view)
  console.log('event', event)
  let creatlayer = {
    id: fist.data.id,
    LayerName: fist.data.LayerName, //图层名称
    ParentId: '',  //父图层id
    KeyValue: fist.data.KeyValue, //图源keyValue标识
    LayerType: fist.data.LayerType //1图层 null或者0是图源
  }

  if (view == 'inner') {
    creatlayer.ParentId = last.data.id
  } else {
    creatlayer.ParentId = last.data.ParentId
  }





  await putLayer(creatlayer)
  await getLayerapi()
}
const handleDocumentClick = (event) => {
  const treeContainer = document.querySelector(".el-tree");
  const clickedInsideTree = treeContainer?.contains(event.target);

  // 如果点击的是 el-tree 以外的区域，移除所有高亮
  if (!clickedInsideTree) {
    clicktree.value = "";
    const currentNodes = document.querySelectorAll(".el-tree-node.is-current");
    currentNodes.forEach((node) => {
      node.classList.remove("is-current");
    });
  }
};

const ribtn = (event, data, node, children) => {
  // 阻止默认右键菜单
  event.preventDefault();
  // 关闭所有节点的右键菜单
  const closeAllPopovers = (nodes) => {
    nodes.forEach((item) => {
      item.popovisible = false;
      item.subPopoverVisible = false
      if (item.Children) {
        closeAllPopovers(item.Children);
      }
    });
  };

  // 关闭所有菜单
  closeAllPopovers(treedata.value);

  // 打开当前节点的菜单
  data.popovisible = true;
  //
  const closeMenu = (e) => {
    if (!event.target.contains(e.target)) {
      data.popovisible = false;
      data.subPopoverVisible = false
      document.removeEventListener("click", closeMenu);
    }
  };

  setTimeout(() => {
    document.addEventListener("click", closeMenu);
  }, 0);
};

const ribtnss = (event, data, node, children) => {
  // 阻止默认右键菜单
  event.preventDefault();
  // 关闭所有节点的右键菜单
  const closeAllPopovers = (nodes) => {
    nodes.forEach((item) => {
      item.popovisible = false;
      item.subPopoverVisible = false
      if (item.Children) {
        closeAllPopovers(item.Children);
      }
    });
  };

  // 关闭所有菜单
  closeAllPopovers(treedata.value);

  // 打开当前节点的菜单
  if (data.Children.length == 0 && data.LayerName != '系统上传目标') {
    data.popovisible = true;
  }
  //
  const closeMenu = (e) => {
    if (!event.target.contains(e.target)) {
      data.popovisible = false;
      data.subPopoverVisible = false
      document.removeEventListener("click", closeMenu);
    }
  };

  setTimeout(() => {
    document.addEventListener("click", closeMenu);
  }, 0);
};

const treepopo = (item, node, data) => {
  const closeAllPopovers = (nodes) => {
    nodes.forEach((item) => {
      item.popochong = true;

      if (item.Children) {
        closeAllPopovers(item.Children);
      }
    });
  };

  // 关闭所有菜单
  closeAllPopovers(treedata.value);

  console.log('item.tit', item.tit)
  switch (item.tit) {
    case '重命名':
      data.popochong = false;
      break;
    case '新建图层':
      ElMessageBoxopen(data)
      break;
    case '新建图元':
      data.subPopoverVisible = true
      break;

    case '删除':

      deleteLayer(data.id).then((e) => {

        getLayerapi()
      })
      break;

    case '删除图层':
      deleteLayer(data.id).then((e) => {
        getLayerapi()
      })

      break;
      ''
    case '编辑':
      proxy.$mitt.emit('Layerdata', data)
      break;
    case '目标消批':
      deleteLayer(data.id).then((e) => {
        getmessagapi()
      })
      break;

    case '目标干预':

      proxy.$mitt.emit('Layerdata', data)

      break;



  }
};



const actpopoImage = (item, node, data) => {
  proxy.$mitt.emit('drawdata', {
    rightd: item,
    treenode: node,
    treedata: data
  })
}
//
const getLayerapi = async () => {
  // 保存当前树的展开状态和选中状态

  const { data } = await getLayer()
  // 递归函数：为所有节点添加默认属性
  const addDefaultProps = (nodes) => {
    return nodes.map(node => {
      // 为当前节点添加属性
      const newNode = {
        ...node,
        popovisible: false,
        popochong: true,
        subPopoverVisible: false
      };

      // 如果有子节点，递归处理
      if (newNode.Children && newNode.Children.length > 0) {
        newNode.Children = addDefaultProps(newNode.Children);
      }
      return newNode;
    });
  };

  // 使用递归函数处理所有层级节点
  treedata.value = addDefaultProps(data)

  // 等待DOM更新后恢复展开和选中状态

}
//
const ElMessageBoxopen = (datashuju) => {
  ElMessageBox.prompt('图层名称：', '新建图层', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    customStyle: {
      width: '300px'
    },
  })
    .then(async ({ value }) => {
      await postAddLayer({
        LayerName: value, //图层名称
        ParentId: datashuju.id,  //父图层id
        LayerType: datashuju.LayerType //1图层 null或者0是图源
      }).then((e) => {

        getLayerapi()
      })
    })
    .catch(() => {

    })
}

// 搜索
const filterText = ref('')

const filterNode = (value, data) => {
  if (!value) return true
  return data.LayerName.includes(value)
}

watch(filterText, (val) => {
  if (treeRef.value) {
    treeRef.value.filter(val)
  }
})








// 纬度切换
const handleContClick = (item) => {
  if (!isnum.value) {
    boxLeft.value = "-" + contItems.value.length * 90 + "px";
    isnum.value = true;
    return;
  }

  // 后续点击逻辑
  actiob.value = item;
  boxLeft.value = "-90px";
  proxy.$mitt.emit("caeatmap", item.name);
  isnum.value = false;
};
const weatherController = ref(null);
const cloudInstance = ref(null);
const handleCloudNodeClick = async (data) => {
  const response = await fetch('/BJ.json');
  const geojson = await response.json();
  switch (data.LayerName) {

    case '云':
      try {
        // 移除已有云实例
        if (cloudInstance.value) {
          cloudInstance.value.destroy()
        }

        // 创建新的云实例
        cloudInstance.value = new CloudManager(window.viewer, {
          geoJsonData: geojson,
          // 配置参数
        });
      } catch (error) {
        console.error('Failed to initialize volume clouds:', error);
        ElMessage.error('云效果初始化失败');
      }
      break;
    case '风':
      // try {
      //   // 加载风场数据（根据实际数据格式调整）
      //   await fetch('./feng.json')
      //     .then(response => response.json())
      //     .then(data => {
      //       // 修改WindLayer构造函数访问方式
      //       debugger
      //       const windLayer = new WindLayer(data);
      //       windLayer.addTo(window.viewer)
      //     });
      // } catch (error) {
      //   console.error('风场图层初始化失败:', error);
      // }
      const oceanCurrentssss = new LayerOceanCurrent();
      await fetch('./hai.json')
        .then(response => response.json())
        .then(data => {

          oceanCurrentssss.load(data.data); // 加载数据
          oceanCurrentssss.addToMap(window.viewer);
        })
        .catch(error => console.error('数据加载失败:', error));
      break
    case '海浪':

      const oceanCurrent = new LayerOceanCurrent();
      await fetch('./hai.json')
        .then(response => response.json())
        .then(data => {

          oceanCurrent.load(data.data); // 加载数据
          oceanCurrent.addToMap(window.viewer);
        })
        .catch(error => console.error('数据加载失败:', error));
      break
    case '雷电':

      const weather = new CesiumWeather(window.viewer);
      // 默认参数
      weather.createLightning();

      // 自定义参数
      weather.createLightning({
        // mix_factor: 0.5, // 混合系数(0-1)，值越大效果越明显
        // fall_interval: 0.6 // 闪电下落间隔(0-1)
      });

      break
  }


};


const getmessagapi = async () => {
  const { data } = await getmessag()


  // 递归函数：为所有节点添加默认属性
  const addDefaultProps = (nodes) => {
    return nodes.map(node => {
      // 为当前节点添加属性
      const newNode = {
        ...node,
        popovisible: false,
        popochong: true,
        subPopoverVisible: false
      };

      // 如果有子节点，递归处理
      if (newNode.Children && newNode.Children.length > 0) {
        newNode.Children = addDefaultProps(newNode.Children);
      }
      return newNode;
    });
  };

  // 使用递归函数处理所有层级节点
  treedata.value = addDefaultProps(data)



}


// 生命周期钩子
onMounted(() => {
  getLayerapi()
  proxy.$mitt.on('getsubmit', (e) => {
    getLayerapi()
  })
  document.addEventListener("click", handleDocumentClick);

  // 初始化 filteredActiveArr
  if (titleStore.rightTitles.length > 0) {
    filteredActiveArr.value = activearr.value.filter(item => titleStore.rightTitles.includes(item.title));
  }

  // 添加对 titleStore.rightTitles 变化的监听
  watch(
    () => titleStore.rightTitles,
    (newTitles) => {
      filteredActiveArr.value = activearr.value.filter(item => newTitles.includes(item.title));
    },
    { deep: true }
  );

  watch(
    () => websocketStore.messages,
    (newMessages) => {
      console.log(websocketStore)

      // getLayerapi()
    },
    { deep: true }
  );
});

onBeforeUnmount(() => {
  // 移除监听
  document.removeEventListener("click", handleDocumentClick);
  // proxy.$mitt.off('updateLeftTitles');
  // proxy.$mitt.off('getCurrentLeftTitles');
  // 清理所有右键菜单状态
  const resetAllPopovers = (nodes) => {
    nodes.forEach((item) => {
      item.popovisible = false;
      item.subPopoverVisible = false
      item.popochong = true;
      if (item.Children) {
        resetAllPopovers(item.Children);
      }
    });
  };

  resetAllPopovers(treedata.value);

});
</script>

<style scoped>
.actbtn {
  border: 1px solid #3370ff;
  border-radius: 4px;
}

.contimg {
  width: 100%;
  height: 100%;
}

.contimg-span {
  line-height: 80px;
  color: black
}

.iconimg {
  position: absolute;
  bottom: 0;
  right: 0;
}

.cont {
  cursor: pointer;
  width: 80px;
  height: 80px;
  position: relative;
  text-align: center;
  top: 12px;
  margin: 0 6px;
}

.cont:last-child {
  margin-right: 12px;
}

.cont:first-child {
  margin-left: 12px;
}

.lvlantubox {
  position: absolute;
  bottom: 100px;
  /* bottom: 86px; */
  height: 104px;
  /* width: 104px; */
  background: rgba(255, 255, 255, 0.6);
  left: -90px;
  /* left: -257px; */
  display: flex;
  border-radius: 4px;
}

.X_Plot_content {
  position: absolute;
  width: 400px;
  /* height: 100%; */
  height: 80%;
  top: 118px;
  right: 0;
}

.X_Plot_content_right {
  position: relative;
  /* height: 100% */
  height: 80%
}

.X_Plot_right {
  position: absolute;
  right: 30px;
  width: 330px;
  /* height: 869px; */
  height: 80%;
  top: -20px;
}

.X_Plot_right_contcent {
  height: 80vh;
  /* height: 100%; */
  background-image: url("@/assets/img/27/rightbg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  margin-top: 6px;
}




.X_Plot_right_btn {
  width: 74px;
  margin-right: 8px;
}

.X_Plot_right_btn_title {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.32);
}

:deep(.el-tree) {
  background: none;
  color: #a8d6ff;
}

/* 鼠标浮动过的背景颜色 */
:deep(.el-tree-node__content:hover) {
  /* background: rgba(235, 243, 255, 0.10); */
  background: none;
}

:deep(.el-tree-node__content) {
  padding: 0 8px;
  height: 36px;
}

/* :deep(.el-tree-node__children) {
  margin: 20px 0;
} */

:deep(.el-text) {
  color: #a8d6ff;
}

/* 鼠标失去焦点时节点背景的颜色 */
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background: none;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: none;
}

/* 修改点击后的背景色为红色 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(235, 243, 255, 0.1) !important;
  border-radius: 4px;
}

/* 修改点击后的文字颜色（可选） */
/* :deep(.el-tree-node.is-current > .el-tree-node__content .el-tree-node__label) {
  color: white !important;
} */

/* :deep(.is-current) {
  color: red;
  background: red;
} */

:deep(.el-checkbox) {
  z-index: 0;
  margin-bottom: 0;
}

:deep(.el-input__wrapper) {
  border-radius: 16px;
  background: #27598c;
  border: 1px solid #307ac6;
  box-shadow: none;
}

:deep(.el-input__inner::placeholder) {
  color: #6b8db0;
  /* 红色示例 */
  opacity: 1;
  /* 修复 Firefox 的默认透明度问题 */
}

:deep(.el-input__inner) {
  color: #fff;
  /* 红色示例 */
}

/*  */

/* 右键菜单样式 */
.custom-context-menu {
  padding: 0 !important;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.menu-content {
  min-width: 120px;
  padding: 5px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.menu-item i {
  margin-right: 8px;
  font-size: 14px;
}

:deep(.el-popover.el-popper) {
  min-width: 114px !important;
}

:deep(.treeinput .el-input__wrapper) {
  border: none;
  background: none;
}
</style>